<template>
  <div class="pollution-management">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline label-width="150px">
        <el-form-item label="排污口名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入名称"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            style="margin-top: 10px"
          >
            新增排污口
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        border
        stripe
        ref="table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="outfallname" label="排口名称" min-width="180"
          ><template slot-scope="scope">
            <span class="dmmc" @click="handlePkView(scope.row)">{{
              scope.row.outfallname
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="outfallnum"
          label="排口编号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="outfallcode"
          label="排口编码"
          width="120"
        ></el-table-column>
        <!-- <el-table-column
          prop="county"
          label="行政区划"
          width="150"
        ></el-table-column> -->
        <el-table-column
          prop="finallydischargedwater"
          label="受纳水体"
          width="120"
        ></el-table-column>
        <!-- <el-table-column
          prop="responsibilitySubject"
          label="责任主体"
          min-width="150"
        ></el-table-column> -->
        <el-table-column prop="state" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state == '1' ? 'success' : 'info'">
              {{ scope.row.state == 1 ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="mini" @click="handleView(scope.row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑/查看 共用弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="1200px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        class="form-container"
      >
        <!-- 基础信息 -->
        <div class="form-group-title">基础信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排口名称" prop="outfallname">
              <el-input
                v-model="formData.outfallname"
                :disabled="isView"
                placeholder="请输入排口名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排口编号" prop="outfallnum">
              <el-input
                v-model="formData.outfallnum"
                :disabled="isView"
                placeholder="请输入排口编号"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排口编码" prop="outfallcode">
              <el-input
                v-model="formData.outfallcode"
                :disabled="isView"
                placeholder="请输入排口编码"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="行政区划" prop="county">
              <el-select
                style="width: 100%"
                v-model="formData.county"
                :disabled="isView"
                placeholder="请选择行政区划"
                clearable
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="流域名称" prop="basin">
              <el-select
                style="width: 100%"
                v-model="formData.basin"
                :disabled="isView"
                placeholder="请选择流域名称"
                clearable
              >
                <el-option
                  v-for="dict in basinOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经度" prop="longitude">
              <el-input
                v-model="formData.longitude"
                :disabled="isView"
                placeholder="请输入经度"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="纬度" prop="latitude">
              <el-input
                v-model="formData.latitude"
                :disabled="isView"
                placeholder="请输入纬度"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="formData.address"
                :disabled="isView"
                placeholder="请输入详细地址"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 水体、水功能区及分类信息 -->
        <div class="form-group-title">水体、水功能区及分类信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="受纳水体" prop="finallydischargedwater">
              <el-input
                v-model="formData.finallydischargedwater"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入河方式" prop="riverEntryMode">
              <el-select
                style="width: 100%"
                v-model="formData.riverEntryMode"
                :disabled="isView"
                placeholder="请选择入河方式"
                clearable
              >
                <el-option
                  v-for="item in dict.type.in_river_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="最终汇入水体名称"
              prop="finallydischargedwater"
            >
              <el-input
                v-model="formData.finallydischargedwater"
                :disabled="isView"
                placeholder="请输入最终汇入水体名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="周边环境" prop="round">
              <el-input
                v-model="formData.round"
                :disabled="isView"
                placeholder="请输入周边环境"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="一级水功能区名称" prop="onewatername">
              <el-input
                v-model="formData.onewatername"
                :disabled="isView"
                placeholder="请输入一级水功能区名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排入水功能区名称" prop="waterfuncname">
              <el-input
                v-model="formData.waterfuncname"
                :disabled="isView"
                placeholder="请输入排入水功能区名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排入水功能区水质目标" prop="waterfunctarget">
              <el-input
                v-model="formData.waterfunctarget"
                :disabled="isView"
                placeholder="请输入排入水功能区水质目标"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="二级水功能区名称" prop="twowatername">
              <el-input
                v-model="formData.twowatername"
                :disabled="isView"
                placeholder="请输入二级水功能区名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联国控断面" prop="relatedNationalSection">
              <el-select
                style="width: 100%"
                v-model="formData.relatedNationalSection"
                :disabled="isView"
                placeholder="请选择关联国控断面"
                clearable
              >
                <el-option label="蚌埠闸上" value="蚌埠闸上"></el-option>
                <el-option label="巢湖西半湖" value="巢湖西半湖"></el-option>
                <el-option
                  label="南京长江大桥"
                  value="南京长江大桥"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="关联国控断面水质目标" prop="segqualitytarget">
              <el-input
                v-model="formData.segqualitytarget"
                :disabled="isView"
                placeholder="请输入关联国控断面水质目标"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="排污口一级分类"
              prop="outfallfirstclassifycode"
            >
              <el-select
                style="width: 100%"
                v-model="formData.outfallfirstclassifycode"
                :disabled="isView"
                placeholder="请选择排污口一级分类"
                clearable
              >
                <el-option
                  v-for="item in dict.type.rh_type_first"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排污口二级分类" prop="outfallsecondclassify">
              <el-select
                style="width: 100%"
                v-model="formData.outfallsecondclassify"
                :disabled="isView"
                placeholder="请选择排污口二级分类"
                clearable
              >
                <el-option
                  v-for="item in dict.type.rh_type_second"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排污口三级分类" prop="outfallthirdclassify">
              <el-select
                style="width: 100%"
                v-model="formData.outfallthirdclassify"
                :disabled="isView"
                placeholder="请选择排污口三级分类"
                clearable
              >
                <el-option
                  v-for="item in dict.type.rh_type_third"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排口形态" prop="mouthdoor">
              <el-select
                style="width: 100%"
                v-model="formData.mouthdoor"
                :disabled="isView"
                placeholder="请选择排口形态"
                clearable
              >
                <el-option
                  v-for="item in dict.type.rh_mouthdoor"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排水特征" prop="drainagenafeature">
              <el-select
                style="width: 100%"
                v-model="formData.drainagenafeature"
                :disabled="isView"
                placeholder="请选择排水特征"
                clearable
              >
                <el-option
                  v-for="item in dict.type.drainagena_feature"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排放方式" prop="outtype">
              <el-select
                style="width: 100%"
                v-model="formData.outtype"
                :disabled="isView"
                placeholder="请选择排放方式"
                clearable
              >
                <el-option
                  v-for="item in dict.type.rh_outtype"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="污水排水量" prop="displacements">
              <el-input
                v-model="formData.displacements"
                :disabled="isView"
                placeholder="请输入污水排水量"
                maxlength="20"
              ></el-input>
              <span class="unit-text">（万吨/年）</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排口类型" prop="outfalltype">
              <el-select
                style="width: 100%"
                v-model="formData.outfalltype"
                :disabled="isView"
                placeholder="请选择排口类型"
                clearable
              >
                <el-option
                  v-for="item in dict.type.out_fall_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排口规模" prop="outfallscale">
              <el-input
                v-model="formData.outfallscale"
                :disabled="isView"
                placeholder="请输入排口规模"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有无异常状况" prop="ifabnormal">
              <el-radio-group v-model="formData.ifabnormal" :disabled="isView">
                <el-radio label="1">有</el-radio>
                <el-radio label="0">无</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 溯源信息 -->
        <div class="form-group-title">溯源信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="责任主体类型" prop="responsibilitySubjectType">
              <el-select
                style="width: 100%"
                v-model="formData.responsibilitySubjectType"
                :disabled="isView"
                placeholder="请选择责任主体类型"
                clearable
              >
                <el-option label="企业" value="企业"></el-option>
                <el-option label="事业单位" value="事业单位"></el-option>
                <el-option label="政府部门" value="政府部门"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任主体" prop="responsibilitySubject">
              <el-input
                v-model="formData.responsibilitySubject"
                :disabled="isView"
                placeholder="请输入责任主体"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管理单位" prop="setunits">
              <el-input
                v-model="formData.setunits"
                :disabled="isView"
                placeholder="请输入责任主体"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="设置时间" prop="setunitstime">
              <el-date-picker
                v-model="formData.setunitstime"
                :disabled="isView"
                type="date"
                placeholder="请选择设置时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规范化建设" prop="standardconstruction">
              <el-select
                style="width: 100%"
                v-model="formData.standardconstruction"
                :disabled="isView"
                placeholder="请选择规范化建设情况"
                clearable
              >
                <el-option
                  v-for="item in dict.type.normalize_construction"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审批登记情况" prop="applycondition">
              <el-input
                v-model="formData.applycondition"
                :disabled="isView"
                placeholder="请输入审批登记情况"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="批复文号" prop="wh">
              <el-input
                v-model="formData.wh"
                :disabled="isView"
                placeholder="请输入批复文号"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批复日期" prop="applydate">
              <el-date-picker
                v-model="formData.applydate"
                :disabled="isView"
                type="date"
                placeholder="请选择批复日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批复（设置）要求" prop="reqapply">
              <el-input
                v-model="formData.reqapply"
                :disabled="isView"
                placeholder="请输入批复（设置）要求"
                maxlength="200"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="执行标准/排放标准" prop="execstandard">
              <el-input
                v-model="formData.execstandard"
                :disabled="isView"
                placeholder="请输入执行标准/排放标准"
                maxlength="200"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排放标准级别" prop="standardlevel">
              <el-select
                style="width: 100%"
                v-model="formData.standardlevel"
                :disabled="isView"
                placeholder="请选择排放标准级别"
                clearable
              >
                <el-option label="一级" value="一级"></el-option>
                <el-option label="二级" value="二级"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="formData.state" :disabled="isView">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="formData.remarks"
                :disabled="isView"
                type="textarea"
                placeholder="请输入备注信息"
                rows="3"
                maxlength="500"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传" prop="file">
              <div class="langcont-left" style="position: relative">
                <el-upload
                  :action="baseUrl + '/common/upload'"
                  :headers="headers"
                  accept="image/jpeg,image/gif,image/png,image/jpg"
                  list-type="picture-card"
                  :limit="1"
                  :class="ImageUrlList.length > 0 || disabled ? 'hide' : ''"
                  :file-list="ImageUrlList"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :disabled="disabled || title === '查看排口信息'"
                  :before-upload="beforeUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <div class="demo-image__preview" style="display: none">
                  <el-image
                    style="width: 100px; height: 100px"
                    class="myImg"
                    ref="myImg"
                    :src="ImagePreview[0]"
                    :preview-src-list="ImagePreview"
                  >
                  </el-image>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 弹框底部按钮：根据 isView 切换显示 -->
      <div slot="footer">
        <template v-if="isView">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </template>
        <template v-else>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </div>
    </el-dialog>
    <!-- 排口名称点击弹框 -->
    <el-dialog
      title="排口信息"
      :visible.sync="ShowPk"
      width="1000px"
      :close-on-click-modal="false"
    >
      <Details :outletName="outletName" :pkid="rowid" />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getRegionList } from "@/api/dataResources/monitorData/region.js";
import { getBasinSelect } from "@/api/dataResources/monitorData/section.js";
import {
  getResponsibilityList,
  getResponsibilityDetail,
  addResponsibility,
  editResponsibility,
} from "@/api/traceability";
import Details from "./details.vue";
export default {
  name: "PollutionOutletManagement",
  components: {
    Details: () => import("./details.vue"),
  },
  dicts: [
    "in_river_type",
    "rh_type_first",
    "rh_type_second",
    "rh_type_third",
    "rh_mouthdoor",
    "drainagena_feature",
    "rh_outtype",
    "out_fall_type",
    "normalize_construction",
  ],
  data() {
    return {
      // 查询表单
      searchForm: {
        name: "",
      },
      // 表格数据
      tableData: [],
      // 分页信息
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 弹窗控制 + 查看模式标识
      dialogVisible: false,
      title: "新增排污口",
      isView: false, // true = 查看模式，false = 编辑/新增模式
      // 表单数据（与图片字段一一对应）
      formData: {
        outfallname: "",
        outfallnum: "",
        outfallcode: "",
        county: "",
        basin: "",
        longitude: "",
        latitude: "",
        address: "",
        finallydischargedwater: "",
        riverEntryMode: "",
        finalWaterName: "",
        round: "",
        onewatername: "",
        waterfuncname: "",
        waterfunctarget: "",
        twowatername: "",
        relatedNationalSection: "",
        segqualitytarget: "",
        outfallfirstclassifycode: "",
        outfallsecondclassify: "",
        outfallthirdclassify: "",
        mouthdoor: "",
        drainagenafeature: "",
        outtype: "",
        displacements: "",
        outfalltype: "",
        outfallscale: "",
        ifabnormal: "",
        responsibilitySubjectType: "",
        responsibilitySubject: "",
        setunits: "",
        setunitstime: null,
        standardconstruction: "",
        applycondition: "",
        wh: "",
        applydate: null,
        reqapply: "",
        execstandard: "",
        standardlevel: "",
        state: "启用",
        remarks: "",
        outletImage: [], // 上传图片列表
      },
      // 表单验证规则（必填字段加`*`）
      formRules: {
        outfallname: [
          { required: true, message: "请输入排口名称", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "排口名称长度在2-50个字符之间",
            trigger: "blur",
          },
        ],
        county: [
          { required: true, message: "请选择行政区划", trigger: "change" },
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
          {
            pattern: /^-?\d+(\.\d{1,6})?$/,
            message: "请输入有效的经度值",
            trigger: "blur",
          },
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          {
            pattern: /^-?\d+(\.\d{1,6})?$/,
            message: "请输入有效的纬度值",
            trigger: "blur",
          },
        ],
        finallydischargedwater: [
          { required: true, message: "请选择受纳水体", trigger: "change" },
        ],
        outfallfirstclassifycode: [
          {
            required: true,
            message: "请选择排污口一级分类",
            trigger: "change",
          },
        ],
        outfallsecondclassify: [
          {
            required: true,
            message: "请选择排污口二级分类",
            trigger: "change",
          },
        ],
        responsibilitySubjectType: [
          { required: true, message: "请选择责任主体类型", trigger: "change" },
        ],
        responsibilitySubject: [
          { required: true, message: "请输入责任主体", trigger: "blur" },
        ],
        setunits: [
          { required: true, message: "请选择管理单位", trigger: "change" },
        ],
      },
      // 选中的行
      selectedRows: [],
      regionList: [],
      basinOptions: [],
      // 图片上传相关
      baseUrl: this.$config,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      ImageUrlList: [],
      ImagePreview: [""],
      photoFile: null,
      disabled: false,
      ShowPk: false,
      rowid: "",
      outletName: "",
    };
  },
  created() {
    this.getRegionList();
    this.getssly();
    this.getList();
  },
  methods: {
    // 获取行政区划列表
    async getRegionList() {
      const res = await getRegionList();
      if (res.code === 200) {
        this.regionList = res.rows;
      }
    },
    // 获取所属流域下拉选项数据
    getssly() {
      getBasinSelect().then((response) => {
        console.log(">>>流域", response);

        this.basinOptions = response.rows.map((item) => ({
          value: item.id,
          label: item.basinname,
        }));
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.ImagePreview[0] = file.url;
      this.$refs.myImg.showViewer = true;
    },
    // 图片上传成功
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.ImageUrlList = [];
        fileList.forEach((item) => {
          if (item.response) {
            this.ImageUrlList.push(item.response);
          } else {
            this.ImageUrlList.push(item);
          }
        });
        this.photoFile = response.fileName;
      }
    },
    // 图片移除
    handleRemove(file, fileList) {
      this.ImageUrlList = [];
      this.photoFile = null;
      fileList.forEach((item) => {
        if (item.response) {
          this.ImageUrlList.push(item.response);
        } else {
          this.ImageUrlList.push(item);
        }
      });
    },
    // 上传前校验
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt500k = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt500k) {
        this.$message.error("上传图片大小不能超过 500KB!");
      }
      return isJPG && isLt500k;
    },
    // 查询
    handleSearch() {
      console.log("查询参数:", this.searchForm);
      this.getList();
    },
    // 重置查询
    resetSearch() {
      this.searchForm = {
        name: "",
      };
      this.handleSearch();
    },
    // 新增（编辑模式：isView = false）
    handleAdd() {
      this.isView = false;
      this.title = "新增排污口";
      this.formData = {
        state: "启用",
        setunitstime: null,
        applydate: null,
        outletImage: [],
        // 其他字段默认值
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },
    // 编辑（编辑模式：isView = false）
    handleEdit(row) {
      this.isView = false;
      this.title = "修改排污口";
      getResponsibilityDetail(row.id).then((res) => {
        if (res.code === 200) {
          console.log(">>>", res);

          const detail = res.data;
          this.formData = {
            ...detail,
            setunitstime: detail.setunitstime
              ? new Date(detail.setunitstime)
              : null,
            applydate: detail.applydate ? new Date(detail.applydate) : null,
            outletImage: detail.outletImage
              ? [
                  {
                    name: "排污口图片",
                    url: detail.outletImage,
                  },
                ]
              : [],
          };
          this.ImageUrlList = this.formData.outletImage;
          this.photoFile = detail.outletImage || null;
          this.dialogVisible = true;
          this.$nextTick(() => {
            this.$refs.dataForm.clearValidate();
          });
        }
      });
      // const formData = JSON.parse(JSON.stringify(row));
      // formData.setunitstime = row.setunitstime
      //   ? new Date(row.setunitstime)
      //   : null;
      // formData.applydate = row.applydate ? new Date(row.applydate) : null;
      // this.formData = formData;
      // this.dialogVisible = true;
      // this.$nextTick(() => {
      //   this.$refs.dataForm.clearValidate();
      // });
    },
    // 排口名称行间点击事件
    handlePkView(row) {
      console.log(">>>行间的详情啊", row);

      this.ShowPk = true;
      this.rowid = row.id;
      this.outletName = row.outfallname;
    },
    // 查看（查看模式：isView = true）
    handleView(row) {
      this.isView = true;
      this.title = "查看排污口";
      const formData = JSON.parse(JSON.stringify(row));
      formData.setunitstime = row.setunitstime
        ? new Date(row.setunitstime)
        : null;
      formData.applydate = row.applydate ? new Date(row.applydate) : null;
      this.formData = formData;
      this.dialogVisible = true;
    },
    // 提交表单（仅编辑/新增模式触发）
    submitForm() {
      if (this.isView) return; // 查看模式下不提交

      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // 处理日期格式为字符串
          const submitData = {
            ...this.formData,
            setunitstime: this.formData.setunitstime
              ? this.formData.setunitstime.toISOString().split("T")[0]
              : "",
            applydate: this.formData.applydate
              ? this.formData.applydate.toISOString().split("T")[0]
              : "",
          };

          if (this.title === "新增排污口") {
            // 新增（实际需调用接口，此处模拟）
            addResponsibility(submitData).then((res) => {
              if (res.code === 200) {
                // this.tableData.unshift(submitData);
                // this.pagination.total++;
                this.getList();
                this.$message.success("新增成功");
              }
            });
          } else {
            // 修改（实际需调用接口，此处模拟）
            // const index = this.tableData.findIndex(
            //   (item) => item.outfallnum === submitData.outfallnum
            // );
            // if (index !== -1) {
            //   this.tableData.splice(index, 1, submitData);
            // }
            editResponsibility(submitData).then((res) => {
              if (res.code === 200) {
                // this.tableData.splice(index, 1, submitData);
                this.getList();
                this.$message.success("修改成功");
              }
            });
          }
          this.dialogVisible = false;
        }
      });
    },
    // 图片上传变化
    handleImageChange(file, fileList) {
      this.formData.outletImage = fileList;
    },
    // 图片上传前校验
    beforeImageUpload(file) {
      const isImage = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("仅支持jpg、jpeg、png格式的图片");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过2MB");
        return false;
      }
      return true;
    },
    // 分页
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.handleSearch();
    },
    // 选择行变化
    handleSelectionChange(rows) {
      this.selectedRows = rows;
    },
    // 获取表格数据（实际接口调用）
    getList() {
      let query = {
        lakename: "丹河",
        outfallname: this.searchForm.name,
      };
      getResponsibilityList(query).then((res) => {
        this.tableData = res.rows;
        this.pagination.total = res.total;
      });
    },
  },
};
</script>

<style scoped>
.pollution-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 20px;
  background-color: #fff;
}

.table-card {
  background-color: #fff;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.form-container {
  margin-top: 10px;
}

.form-group-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 15px 0 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e6e6e6;
}

.unit-text {
  font-size: 12px;
  color: #666;
  margin-left: 5px;
}

.dmmc {
  font-size: 14px;
  font-weight: bold;
  color: #307eff;
  cursor: pointer;
}

/* 上传组件样式调整 */
.upload-demo {
  margin-top: 5px;
}
</style>
